import {
  request
} from '../../utils/request'
import {
  timestampToTime
} from '../../utils/util'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    typeList: [{
        name: '往期活动'
      },
      {
        name: '打卡签到'
      }
    ],
    weekDates: [],
    list: [{
        label: '比赛',
        key: 'MATCH'
      },
      {
        label: '活动',
        key: 'ACTIVITY'
      },
      {
        label: '课程',
        key: 'COURSE'
      }
    ],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    days: [],
    weekDays: [
      '日',
      '一',
      '二',
      '三',
      '四',
      '五',
      '六'
    ],
    selectedDate: new Date()
      .toLocaleDateString()
      .replace(/\//g, '-'),
    currentDay: '',
    currentToDay: '',
    page: 1,
    size: 10,
    showNoMore: false,
    showLoading: false,
    selectType: 'ACTIVITY',
    selectTypeName: '活动',
    dataList: [],
    selectId: '',
    selectOrderId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  searchConfirm(item) {
    this.setData({
      selectType: item.detail.selectItem,
      selectTypeName: item.detail.selectLabel
    })
    this.setData({
      page: 1,
      size: 10
    })
    this.resetData()
  },

  getHistoryList() {
    request({
      url: '/mini/api/registerReservation/queryHistoryDataList',
      method: 'POST',
      data: {
        activityDate: this.data.currentDay,
        page: this.data.page,
        size: this.data.size,
        type: this.data.selectType
      }
    }).then((resdata) => {
      if (resdata.code == 200) {
        let newData = this.data.showLoading ?
          this.data.dataList.concat(
            resdata.data.data
          ) :
          resdata.data.data
        let showNoMore =
          resdata.data.data.length < 10
        this.setData({
          dataList: newData || [],
          showLoading: false,
          showNoMore: showNoMore
        })
      } else {
        wx.showToast({
          title: resdata.message,
          icon: 'icon'
        })
        this.setData({
          dataList: [],
          showLoading: false,
          showNoMore: false
        })
      }
    })
  },

  selectId(detail) {
    console.log(detail)
    this.setData({
      selectId: detail.currentTarget.dataset.id,
      selectOrderId: detail.currentTarget.dataset.orderid
    })
  },

  signUp() {
    if (
      !this.data.selectOrderId &&
      this.data.selectOrderId.length <= 0
    ) {
      wx.showToast({
        title: '请先选择要签到的项目',
        icon: 'none'
      })
      return
    }
    request({
      url: '/mini/api/registerReservation/checkIn',
      method: 'POST',
      data: {
        orderId: this.data.selectOrderId,
        refId: this.data.selectId,
        type: this.data.selectType
      }
    }).then((resdata) => {
      if (resdata.code == 200) {
        wx.showToast({
          title: '签到成功'
        })
        this.resetData()
      } else {
        wx.showToast({
          title: resdata.message,
          icon: 'none'
        })
      }
    })
  },

  getNeedCheckList() {
    request({
      url: '/mini/api/registerReservation/queryNeedCheckInList',
      method: 'POST',
      data: {
        page: this.data.page,
        size: this.data.size,
        type: this.data.selectType
      }
    }).then((resdata) => {
      if (resdata.code == 200) {
        let newData = this.data.showLoading ?
          this.data.dataList.concat(
            resdata.data.data
          ) :
          resdata.data.data
        let showNoMore =
          resdata.data.data.length < 10
        this.setData({
          dataList: newData || [],
          showLoading: false,
          showNoMore: showNoMore
        })
      } else {
        wx.showToast({
          title: resdata.message,
          icon: 'icon'
        })
        this.setData({
          dataList: [],
          showLoading: false,
          showNoMore: showNoMore
        })
      }
    })
  },

  resetData() {
    this.setData({
      selectId: '',
      selectOrderId: ''
    })
    if (this.data.currentTab == 0) {
      this.getHistoryList()
    } else {
      this.getNeedCheckList()
    }
  },

  formatNumber(n) {
    return n < 10 ? '0' + n : n
  },

  formatDate(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    // 月份从0开始
    const day = date.getDate()
    return `${year}-${month}-${day}`
  },

  /**
   * 获取日历当前月数据日期
   */
  generateCalendar() {
    const {
      year,
      month,
      selectedDate
    } = this.data
    const firstDayOfMonth = new Date(
      year,
      month - 1,
      1
    )
    const lastDayOfMonth = new Date(
      year,
      month,
      0
    )
    const firstDayOfWeek = firstDayOfMonth.getDay()
    const daysInMonth = lastDayOfMonth.getDate()

    let days = []
    let dayCount = 0

    for (let i = 0; i < firstDayOfWeek; i++) {
      const prevMonthDay = new Date(
        year,
        month - 1,
        -i
      )
      days.unshift({
        year: prevMonthDay.getFullYear(),
        month: prevMonthDay.getMonth() + 1,
        day: prevMonthDay.getDate(),
        date: prevMonthDay,
        isCurrentMonth: false,
        isToday: false,
        isSelected: false
      })
      dayCount++
    }

    for (let i = 1; i <= daysInMonth; i++) {
      const date = new Date(year, month - 1, i)
      const dateStr = this.formatDate(date)
      days.push({
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate(),
        date: dateStr,
        isCurrentMonth: true,
        isToday: dateStr === this.formatDate(new Date()),
        isSelected: dateStr === selectedDate
      })
      dayCount++
    }

    for (let i = 1; dayCount % 7 !== 0; i++) {
      const nextMonthDay = new Date(
        year,
        month,
        i
      )
      days.push({
        year: nextMonthDay.getFullYear(),
        month: nextMonthDay.getMonth() + 1,
        day: nextMonthDay.getDate(),
        date: nextMonthDay,
        isCurrentMonth: false,
        isToday: false,
        isSelected: false
      })
      dayCount++
    }

    this.setData({
      days: days
    })
  },

  /**
   * 上个月
   */
  prevMonth() {
    let {
      year,
      month
    } = this.data
    if (month === 1) {
      month = 12
      year--
    } else {
      month--
    }
    this.setData({
        year,
        month
      },
      this.generateCalendar
    )
  },

  /**
   * 下个月
   */
  nextMonth() {
    let {
      year,
      month
    } = this.data
    if (month === 12) {
      month = 1
      year++
    } else {
      month++
    }
    this.setData({
        year,
        month
      },
      this.generateCalendar
    )
  },

  /**
   * 选中日期
   * @param {*} event
   */
  selectDate({
    currentTarget
  }) {
    this.setData({
      currentDay: currentTarget.dataset.item.date
    })
    this.setData({
      page: 1,
      size: 10
    })
    this.resetData()
  },
  /**
   * 获取最近一周
   */
  getWeekDates() {
    const today = new Date()
    this.setData({
      currentDay: timestampToTime(today, 'y+m+d'),
      currentToDay: timestampToTime(
        today,
        'y+m+d'
      )
    })
    const currentDay = today.getDay()

    // 如果是周日，将其视为下一周的开始，即周日为7
    const offset =
      currentDay === 0 ? 6 : currentDay - 1

    // 获取本周的起始日期（周一）
    const startOfWeek = new Date(today)
    startOfWeek.setDate(today.getDate() - offset)

    const weekDates = []
    const daysOfWeek = [
      '一',
      '二',
      '三',
      '四',
      '五',
      '六',
      '日'
    ]

    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = this.formatNumber(
        date.getMonth() + 1
      ) // 月份从0开始
      const day = this.formatNumber(
        date.getDate()
      )
      return `${year}-${month}-${day}`
    }

    for (let i = 0; i < 7; i++) {
      const date = new Date(startOfWeek)
      date.setDate(startOfWeek.getDate() + i)
      const dateStr = formatDate(date) // 格式化日期为 YYYY-MM-DD
      const day = daysOfWeek[i]
      const isToday =
        dateStr === formatDate(new Date())
      const isTomorrow =
        dateStr ===
        formatDate(
          new Date(
            today.setDate(today.getDate() + 1)
          )
        )
      const dayOfMonth = date.getDate() // 获取具体的日期天

      weekDates.push({
        date: dateStr,
        day: day,
        isToday: isToday,
        isTomorrow: isTomorrow,
        dayOfMonth: this.formatNumber(dayOfMonth)
      })

      today.setDate(today.getDate() - 1)
    }

    this.setData({
      weekDates: weekDates
    })
    console.log(weekDates)
    this.getHistoryList()
  },

  onChange({
    detail
  }) {
    this.setData({
      currentTab: detail.index
    })
    this.setData({
      page: 1,
      size: 10
    })
    this.resetData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let app = getApp()
    app.getCurrentTabbar(1, this)
    this.getWeekDates()
    this.generateCalendar()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (
      this.data.showLoading ||
      this.data.showNoMore
    ) {
      return
    }
    let newPage = this.data.page + 1
    this.setData({
      showLoading: true,
      page: newPage
    })
    this.resetData()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})